﻿using System.Collections;
using System.Threading.Tasks;
using TinyPng;
using UnityEngine;

namespace Jinndev {

    public static class TinyPngHelper {

        private static string _ApiKey;
        public static string ApiKey {
            get {
                return _ApiKey;
            }
            set {
                _client = null;
                _ApiKey = value;
            }
        }


        private static TinyPngClient _client;
        public static TinyPngClient Client {
            get {
                if (_client == null && !string.IsNullOrEmpty(ApiKey)) {
                    _client = new TinyPngClient(ApiKey);
                }
                return _client;
            }
        }

        public static Task CompressAsync(string imageFile, string outputFile) {
            return Client.Compress(imageFile)
                         .Download()
                         .SaveImageToDisk(outputFile);
        }

        public static IEnumerator Compress(string imageFile, string outputFile) {
            Task task = Client.Compress(imageFile)
                         .Download()
                         .SaveImageToDisk(outputFile);

            while (!task.IsCompleted) {
                yield return new WaitForSecondsRealtime(0.1f);
            }
        }

    }

}
